﻿using System.Web.Mvc;
using System.Web.Routing;
using Dinamico.Service;
using Dinamico.Models;
using Dynamico.Service;
using N2.Web.Mvc;
using N2.Engine;
using Castle.Windsor;
using N2.Engine.Castle;

namespace Dinamico
{
	// Note: For instructions on enabling IIS6 or IIS7 classic mode, 
	// visit http://go.microsoft.com/?LinkId=9394801

	public class MvcApplication : System.Web.HttpApplication
	{
		public static void RegisterGlobalFilters(GlobalFilterCollection filters)
		{
			filters.Add(new HandleErrorAttribute());
		}

        public static void RegisterRoutes(RouteCollection routes)
		{
			routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            RegisterArticleControllerRoutes(routes);
            RegisterBasketControllerRoutes(routes);

         
			routes.MapRoute(
				"Default", // Route name
				"{controller}/{action}/{id}", // URL with parameters
				new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
			);

		}

        protected void Application_Start()
        {
      

            //        container = new WindsorContainer()
            //.Install(FromAssembly.This());
            //        var controllerFactory = new WindsorControllerFactory(container.Kernel);
            //        ControllerBuilder.Current.SetControllerFactory(controllerFactory);

            RouteTable.Routes.Clear();
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            var container = new WindsorContainer()
          .Install(
              new WindsorInstaller()
          );

            var engine = MvcEngine.Create(new WindsorServiceContainer(container));

            engine.Initialize();
            N2.Context.Replace(engine);

            //RegisterMapper();

                N2.Context.Current.Persister.ItemSaved += new System.EventHandler<N2.ItemEventArgs>(Persister_ItemSaved);
                N2.Context.Current.Persister.ItemDeleting += new System.EventHandler<N2.CancellableItemEventArgs>(Persister_ItemDeleting);
        }
        void Persister_ItemDeleting(object sender, N2.CancellableItemEventArgs e)
        {
            var redirectItem = e.AffectedItem;

            if (redirectItem.Parent != null)
            {

                if (redirectItem.Parent == N2.Find.StartPage)
                {
                    if (redirectItem.Name == "upload")
                    {
                        e.Cancel = true;
                    }
                }
            }
        }

        private static void RegisterBasketControllerRoutes(RouteCollection routes)
        {
            routes.MapRoute(
                Dinamico.Service.Const.Route.RemoveFromBasket,
                Dinamico.Service.Const.Route.RemoveFromBasket + "/{basketId}",
                new { controller = "Basket", action = "RemoveFromBasket" }
           );

            routes.MapRoute(
                Dinamico.Service.Const.Route.Remove_All_From_Basket,
                Dinamico.Service.Const.Route.Remove_All_From_Basket,// "RemoveAllFromBasket",
                new { controller = "Basket", action = "RemoveAllFromBasket" }
            );

            //UpdateBasket
            routes.MapRoute(
                Dinamico.Service.Const.Route.Update_Basket,
                Dinamico.Service.Const.Route.Update_Basket,
                new { controller = "Basket", action = "UpdateBasket" }
            );

            routes.MapRoute(
                Dinamico.Service.Const.Route.Basket_GetUserBasketContent,
                Dinamico.Service.Const.Route.Basket_GetUserBasketContent,
                new { controller = "Basket", action = "GetUserBasketContent" }
            );

            routes.MapRoute(
                Dinamico.Service.Const.Route.Basket_GetUserBasketJsonContent,
                "GetUserBasketJsonContent",
                new { controller = "Basket", action = "GetUserBasketJsonContent" }
            );

            routes.MapRoute(
                Dinamico.Service.Const.Route.Basket_ConfirmOrder,
                "potwierdz_zamowienie",
                new { controller = "Basket", action = "ConfirmOrder" }
            );

            

            routes.MapRoute(
                Dinamico.Service.Const.Route.Basket_VatAndDeliveryText,
                "VatAndDeliveryText",
                new { controller = "Basket", action = "VatAndDeliveryText" }
            );

            routes.MapRoute(
                Dinamico.Service.Const.Route.Basket_List,
                Dinamico.Service.Const.Route.Basket_List,
                new { controller = "Basket", action = "BasketList" }
            );
        }


        private static void RegisterArticleControllerRoutes(RouteCollection routes)
        {
            routes.MapRoute(
               "Hello",
               "Hello",
               new { controller = "Article", action = "Hello" }
           );

            routes.MapRoute(
                "JsonArticles",
                "JsonArticles",
                new { controller = "Article", action = "JsonArticles" }
            );

            routes.MapRoute(
                Dinamico.Service.Const.Route.Article_AddToBasket,
                Dinamico.Service.Const.Route.Article_AddToBasket,
                new { controller = "Article", action = "AddToBasket" }
            );

            routes.MapRoute(
                Dinamico.Service.Const.Route.Article_AddAllIntoBasket,
                Dinamico.Service.Const.Route.Article_AddAllIntoBasket,
                new { controller = "Article", action = "AddAllIntoBasket" }
            );

            routes.MapRoute(
                Dinamico.Service.Const.Route.Article_AddToBasketNoScript,
                "AddToBasketNoScript/{articleId}",
                new { controller = "Article", action = "AddToBasketNoScript" },
                new { articleId = @"\d+" }
            );

            //Category
            routes.MapRoute(
                Dinamico.Service.Const.Route.Article_Category,
                Dinamico.Service.Const.Route.Article_Category + "/{Category}/{page}/{pageSize}",
                new { controller = "Article", action = "Category", page = "1" , pageSize ="50"},
                new { page = @"\d+", pageSize = @"\d+" }

            );
            //
            routes.MapRoute(
                Dinamico.Service.Const.Route.Article_Category_Json,
                Dinamico.Service.Const.Route.Article_Category_Json,
                new { controller = "Article", action = "Article_Category_Json" }
            );

            routes.MapRoute(
                Dinamico.Service.Const.Route.Article_Version_Json,
                Dinamico.Service.Const.Route.Article_Version_Json,
                new { controller = "Article", action = "Article_Version_Json" }
            );


            routes.MapRoute(
               "Import",
               "Import",
            new { controller = "Article", action = "Import" }
            );



            //routes.MapRoute(
            //    Dinamico.Service.Const.Route.Article_,
            //    Resources.Routing.Search,
            //    new { controller = "Article", action = "SearchResults" }
            //);
            //routes.MapRoute(
            //    RouteName.ArticleController.Search_Results_Get,
            //    Resources.Routing.Search + "/{term}/{page}",
            //    new { controller = "Article", action = "SearchResults", page = "1" },
            //    new { page = @"\d+" }
            //);

            //routes.MapRoute(//this is child action
            //    RouteName.ArticleController.List_Child,
            //    "IndexChild/{" + CommonConst.Article.CATEGORY_ROUTE_DATA_KEY + "}/{isVirtual}/{page}",
            //    new { controller = "Article", action = "IndexChild", page = "1" },
            //    new { page = @"\d+" }
            //);

            //routes.MapRoute(//this is child action
            //    RouteName.ArticleController.Details_Child,
            //    "ArticleDetailsChild/{articleID}",
            //    new { controller = "Article", action = "DetailsChild" },
            //    new { articleID = @"\d+" }
            //);

            //routes.MapRoute(
            //    RouteName.ArticleController.List,
            //    "{" + CommonConst.Article.CATEGORY_ROUTE_DATA_KEY + "}/{page}",
            //    new { controller = "Article", action = "Index", page = "1" },
            //    new { page = @"\d+" }
            //);

            //routes.MapRoute(
            //    RouteName.ArticleController.Details,
            //    "{" + CommonConst.Article.CATEGORY_ROUTE_DATA_KEY + "}/{encodedName}",
            //    new { controller = "Article", action = "Details", encodedName = "" }
            //);
        }

        /// <summary>
        ///  This is place  where N2 "SAVE AND PUBLISH" 
        ///  can be overload when examle
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Persister_ItemSaved(object sender, N2.ItemEventArgs e)
        {

        //    e.AffectedItem.Name = Utils.GetEncodedName(e.AffectedItem.Title);

        }
	}
}